package com.blq.snblib.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * ================================================
 * 作者: SSNB
 * 日期: 2016/9/18
 * 描述:
 * 加密工具 MD5 和 SHA
 * ================================================
 */
public class EncryptionUtil {
    public static String MD5 = "MD5";
    public static String SHA = "SHA";

    /**
     * MD5加密
     * @param message 待加密数据
     * @return 加密完成后的数据 27:52:6F:FE:2D:3C:4A:34:6E:E3:A3:08:82:36:35:E1
     */
    public static String encryptMD5(String message){
        return encryptByStyle(MD5,message,null);
    }

    /**
     * SHA加密
     * @param message 待加密数据
     * @return 加密完成后的数据 5D:23:15:F5:E2:E1:73:92:68:6E:78:0D:C6:50:02:DA:0A:B8:24:59
     */
    public static String encryptSHA(String message){
        return encryptByStyle(SHA,message,null);
    }

    /**
     * MD5加密 同时添加混淆因子
     * @param message 待加密数据
     * @param confusion 混淆因子
     * @return 加密完成后的数据 27:52:6F:FE:2D:3C:4A:34:6E:E3:A3:08:82:36:35:E1
     */
    public static String encryptMD5Confusion(String message,int[] confusion){
        return encryptByStyle(MD5,message,confusion);
    }

    /**
     * SHA加密 同时添加混淆因子
     * @param message 待加密数据
     * @param confusion 混淆因子
     * @return 加密完成后的数据 5D:23:15:F5:E2:E1:73:92:68:6E:78:0D:C6:50:02:DA:0A:B8:24:59
     */
    public static String encryptSHAWithConfusion(String message,int[] confusion){
        return encryptByStyle(SHA,message,confusion);
    }

    private static String encryptByStyle(String algorithm , String message,int[] confusion){
        if(message==null){
            throw new IllegalAccessError("message is null");
        }
        String value;
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            md.update(message.getBytes());
            value = byte2hex(md.digest(),confusion);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new IllegalAccessError("加密出错");
        }
        return value;
    }

    private static String byte2hex(byte[] b,int[] confusion){
        String hs = "";
        String temp ;
        boolean isConfusion = confusion!=null;

        for (int i = 0;i<b.length;i++){
            if(isConfusion){
                temp = Integer.toHexString(b[i]&0xFF&confusion[i%confusion.length]);
            }else{
                temp = Integer.toHexString(b[i]&0xFF);
            }

            if(temp.length()==1){
                hs=hs+"0"+temp;
            }else{
                hs=hs+temp;
            }
            if(i<b.length-1){
                hs=hs+":";
            }
        }
        return hs.toUpperCase();
    }
}
